package com.snail.generator.mapper.impl;

import com.snail.generator.entity.ColumnInfo;
import com.snail.generator.entity.TableInfo;
import com.snail.generator.mapper.GeneratorMapper;
import com.snail.generator.utils.SqlUtils;
import lombok.SneakyThrows;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

@Repository
public class MysqlGeneratorMapper implements GeneratorMapper {
    @Override
    @SneakyThrows
    public List<String> queryDatabase() {
        String sql = "show databases";
        List<String> databaseList = new ArrayList<>();
        SqlUtils.execute(sql, resultSet -> {
            while (resultSet.next()) databaseList.add(resultSet.getString(1));
        });
        return databaseList;
    }

    @Override
    @SneakyThrows
    public List<TableInfo> queryTable() {
        String sql = "select table_name, table_comment, create_time from information_schema.tables where table_schema = (select database())";
        List<TableInfo> tableList = new ArrayList<>();
        SqlUtils.execute(sql, resultSet -> {
            while (resultSet.next()) {
                TableInfo tableInfo = new TableInfo(resultSet.getString(1), resultSet.getString(2));
                tableList.add(tableInfo);
            }
        });
        return tableList;
    }

    @Override
    public List<ColumnInfo> queryColumn(String tableName) {
        String sql = """
                select table_name, column_name, data_type, column_comment, column_key, extra
                from information_schema.columns
                where table_schema = (select database())
                and table_name = ?
                order by ordinal_position
                """;
        List<ColumnInfo> columnList = new ArrayList<>();
        SqlUtils.execute(sql, Collections.singletonList(tableName), resultSet -> {
            while (resultSet.next()) {
                ColumnInfo columnInfo = new ColumnInfo(
                        resultSet.getString(1),
                        resultSet.getString(2),
                        resultSet.getString(3),
                        resultSet.getString(4),
                        resultSet.getString(5),
                        resultSet.getString(6)
                );
                columnList.add(columnInfo);
            }
        });
        return columnList;
    }
}
